package data.dictionary.saver;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;

import data.dictionary.Dictionary_Memory;
import data.dictionary.Dictionary_Memory_FilterRareWord;
import data.set.OfflineSetIterator;

public class DictionarySaverWithoutRareWords<T> {
	private String filename;
	private Dictionary_Memory<T> dico;
	private int nFilter, minLength;

	/**
	 * Save dictionary in filename. Rare word are eliminated as well as very short words.
	 * @param filename
	 * @param dico
	 * @param nFilter
	 * @param minLength
	 */
	public DictionarySaverWithoutRareWords(String filename, 
			Dictionary_Memory<T> dico,
			int nFilter, int minLength) {
		super();
		this.filename = filename;
		this.dico = dico;
		this.nFilter = nFilter;
		this.minLength = minLength;
	}

	private void save(PrintStream p) {
		
		OfflineSetIterator<T> iter = dico.inputsetiterator();
		int cpt = 0;
		
		ArrayList<Integer> occ=dico.getCountWords();
		
		while(iter.hasNext()) {
			iter.next();
			
			if(occ.get(iter.getCurrentId())>nFilter)
				
				if(iter.getCurrentObject() instanceof String && 
						((String) iter.getCurrentObject()).length()>=minLength)
					p.println(iter.getCurrentObject()); // 1 par ligne
			else
				cpt++;
		}
		
		System.out.println("saved ("+cpt+" words eliminated)");
		
	}

	public void save() {
		try {
			FileOutputStream output = new FileOutputStream(filename);
			PrintStream p = new PrintStream(output);
			
			
			save(p);

			output.close();
		} catch (IOException e) {
			System.err.println("Can't open file " + filename
					+ " for writting... Saving aborted");

		}
	}

}
